package com.gz.moreaseManager.modules.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.gz.moreaseManager.config.SelfUserDetails;
import com.gz.moreaseManager.core.base.Constants;
import com.gz.moreaseManager.core.modal.AjaxResult;
import com.gz.moreaseManager.core.modal.HttpCode;
import com.gz.moreaseManager.core.modal.PageResult;
import com.gz.moreaseManager.modules.entity.AuthInfo;
import com.gz.moreaseManager.modules.service.IAuthInfoService;
import com.gz.moreaseManager.modules.service.IMenuWebService;
import com.gz.moreaseManager.utils.DateUtil;
import com.gz.moreaseManager.utils.UtilTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import com.gz.moreaseManager.core.base.BaseController;
import org.springframework.web.servlet.ModelAndView;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 会员信息 前端控制器
 * </p>
 *
 * @author wike
 * @since 2019-02-26
 */
@RestController
@RequestMapping("/authInfo")
public class AuthInfoController extends BaseController {

    @Autowired
    private IAuthInfoService authInfoService;
    @Autowired
    private IMenuWebService menuWebService;

    @RequestMapping("list")
    public ModelAndView list(){
        return new ModelAndView("modules/authInfo/list");
    }

    @GetMapping("add")
    public ModelAndView add(){
        return new ModelAndView("modules/authInfo/add");
    }

    @GetMapping("update")
    public ModelAndView update(Integer id){
        AuthInfo authInfo = authInfoService.selectById( id );
        ModelAndView module = new ModelAndView("modules/authInfo/update");
        module.addObject("authInfo",authInfo);
        return module;
    }

    @GetMapping("listPage")
    public PageResult<AuthInfo> findPageLsit(String name, Integer type,
                                             @DateTimeFormat(pattern = "yyyy-MM-dd")Date startDate,
                                             @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDate,
                                             Integer pageNum, Integer pageSize){
        //分页
        Page paramsPage = new Page();
        paramsPage.setCurrent(pageNum);
        paramsPage.setSize(pageSize);
        //构建查询
        Wrapper wrapper = new EntityWrapper<AuthInfo>();
        if( UtilTool.isNotBlank( name ))
            wrapper.like("title",name);
        if( UtilTool.isNotBlank( type ))
            wrapper.eq("type",type);
        if( UtilTool.isNotBlank( startDate ) ){
            if( UtilTool.isNotBlank( endDate ) && startDate.getTime() == endDate.getTime() ){
                wrapper.between("create_time",startDate,DateUtil.addDays(startDate,1));
            }else{
                wrapper.between("create_time",startDate,
                        UtilTool.isNotBlank(endDate)?DateUtil.addDays(endDate,1):DateUtil.addDays(new Date(),1));
            }
        }

        if( UtilTool.isBlank(startDate) && UtilTool.isNotBlank( endDate )){
            wrapper.le("create_time",DateUtil.addDays(endDate,1));
        }
        //排序
        wrapper.orderBy("create_time",false);
        Page<AuthInfo> data = authInfoService.selectPage(paramsPage,wrapper);
        return new PageResult(0, null, data.getTotal(), data.getRecords());

    }

    /**
     * 新增会员
     * @param authInfo
     * @return
     */
    @PostMapping("addAuthInfo")
    public AjaxResult<Boolean> addAuthInfo(@RequestBody AuthInfo authInfo ,Authentication authentication){

        if( authInfo == null
                || UtilTool.isBlank( authInfo.getTitle())
                || UtilTool.isBlank( authInfo.getType()))
            return AjaxResult.build(HttpCode.ARGS_ERROR, "请求参数错误!");

        //查询会员章程只能新增一条
        if( UtilTool.isNotBlank( authInfo.getType() )) {
            Map<Integer, String> authCodeMap = menuWebService.menuWebAuthCodeMap();
            if (authCodeMap.get(authInfo.getType()).equals(Constants.AUTH_TYPE_CONSTITUTION)) {
                //查询是否已经存在记录
                Wrapper<AuthInfo> queryData = new EntityWrapper<AuthInfo>();
                queryData.eq("type", authInfo.getType());
                AuthInfo oldAuth = authInfoService.selectOne(queryData);
                if (UtilTool.isNotBlank(oldAuth))
                    return AjaxResult.build(HttpCode.ARGS_ERROR, "会员章程类型数据已存在!");
            }
        }
        //创建人
        SelfUserDetails userDetails = (SelfUserDetails) authentication.getPrincipal();
        authInfo.setCreatePerson( userDetails.getUsername());
        authInfo.setCreateTime(new Date());
        Boolean success = authInfoService.insert(authInfo);
        return success ? AjaxResult.success() : AjaxResult.build(HttpCode.FAILED, "新增会员信息失败!");
    }

    /**
     * 获取会员信息
     * @param id
     * @return
     */
    @GetMapping("findAuthInfo")
    public AjaxResult<AuthInfo> findInformation( Integer id ){
        if( UtilTool.isBlank( id ))
            return AjaxResult.build(HttpCode.ARGS_ERROR, "请求参数错误!");

        AuthInfo authInfo = authInfoService.selectById( id );
        return AjaxResult.success(authInfo);

    }

    /**
     * 修改会员
     * @param authInfo
     * @return
     */
    @PostMapping("editAuthInfo")
    public AjaxResult<Boolean> editAuthInfo(@RequestBody AuthInfo authInfo){
        if( authInfo == null
                || UtilTool.isBlank( authInfo.getId())
                || UtilTool.isBlank( authInfo.getTitle())
                || UtilTool.isBlank( authInfo.getType()))
            return AjaxResult.build(HttpCode.ARGS_ERROR, "请求参数错误!");

        //查询会员章程只能新增一条
        if( UtilTool.isNotBlank( authInfo.getType() ) && UtilTool.isNotBlank( authInfo.getId())) {
            Map<Integer, String> authCodeMap = menuWebService.menuWebAuthCodeMap();
            if (authCodeMap.get(authInfo.getType()).equals(Constants.AUTH_TYPE_CONSTITUTION)) {
                //查询是否已经存在记录
                Wrapper<AuthInfo> queryData = new EntityWrapper<AuthInfo>();
                queryData.eq("type", authInfo.getType());
                queryData.ne("id", authInfo.getId());
                AuthInfo oldAuth = authInfoService.selectOne(queryData);
                if (UtilTool.isNotBlank(oldAuth))
                    return AjaxResult.build(HttpCode.ARGS_ERROR, "会员章程类型数据已存在!");
            }
        }
        Boolean success = authInfoService.updateById(authInfo);
        return success ? AjaxResult.success() : AjaxResult.build(HttpCode.FAILED, "修改会员信息失败!");
    }

    /**
     * 根据ID删除会员信息
     * @param id
     * @return
     */
    @PostMapping("delete")
    public AjaxResult<Boolean> delete( Integer id){

        if( UtilTool.isBlank( id ))
            return AjaxResult.build(HttpCode.ARGS_ERROR, "请求参数错误!");

        Boolean success = authInfoService.deleteById( id );
        return success ? AjaxResult.success() : AjaxResult.build(HttpCode.FAILED, "删除会员信息失败!");
    }

    /**
     * 获取会员章程信息
     * @return
     */
    @GetMapping("findAuthConstitution")
    public AjaxResult<AuthInfo> findAuthConstitution(){
        AuthInfo authInfo = authInfoService.findAuthConstitution();
        if( UtilTool.isNotBlank( authInfo ))
            return AjaxResult.success(authInfo);
        return AjaxResult.build(HttpCode.FAILED, "获取会员章程信息失败!");
    }

    /**
     * 获取会员活动信息
     * @return
     */
    @GetMapping("findAuthActivity")
    public AjaxResult<List<AuthInfo>> findAuthActivity(){
        List<AuthInfo> authInfoList = authInfoService.findAuthActivity();
        if( UtilTool.isNotBlank( authInfoList ))
            return AjaxResult.success(authInfoList);
        return AjaxResult.build(HttpCode.FAILED, "获取会员活动信息失败!");
    }
}
